package com.e5.action;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.e5.dao.UserDao;
import com.e5.model.User;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport  {
	private String account;
	private String email;
	private String password;
	
	public String execute() {
		User user=new User();
		user.setAccount(account);
		user.setPassword(password);
		user.setEmail(email);
		UserDao userDao =new UserDao();
		if (userDao.check(user)) {
			return "login_success";
		}else {
			this.addFieldError("login_error", this.getText("login.user_login_wrong_account_or_pwd"));
			return "login_fail";
		}
		
	}

	public String getAccount() {
		return account;
	}

	public String getEmail() {
		return email;
	}
	
	public String getPassword() {
		return password;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public void validate() {
		System.out.println("LoginAction.validate...");
		if (account.trim().equals("") || account.trim() == null) {
			this.addFieldError("login_error", this.getText("login.user_login_account_not_null_info", new String[]{"login.user_name"}));
		} 
		if (password.trim().equals("") || password.trim() == null) {
			this.addFieldError("login_error", this.getText("login.user_login_pwd_is_null"));
		}
		if (password.length() < 4 || password.length() > 6) {
			this.addFieldError("login_error", this.getText("login.user_login_set_password_length"));
		}
		String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(email);
		if (!matcher.matches()) {
			this.addFieldError("login_error", this.getText("login.user_login_email_format_incorrect"));
		}
		super.validate();
	}
}
